package com.xiaoming.service;

import com.xiaoming.bean.Employee;
import com.xiaoming.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.Cache;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.stereotype.Service;

/**
 * @author xiaoming
 * @date 2021-03-24 21:27
 */
@Service
//@CacheConfig(cacheManager = "employeeCacheManager")
public class EmployeeService {
    @Autowired
    EmployeeMapper employeeMapper;

    /**
     * 将方法的运行结果进行缓存；以后再要相同的数据，直接从缓存中获取，不用调用方法；
     *  CacheManager管理多个Cache组件的，对缓存的真正CRUD操作在Cache组件中，每一个缓存组件有自己唯一一个名字；
     *  "#root.method.name + '[' + #id + ']'"  --> getEmp[1]
     */
//    @Cacheable(value = {"emg"}, key = "#root.method.name + '[' + #id + ']'")
    // 指定自定义的 CacheManager
    @Cacheable(value = {"emg"}, key = "#id", cacheManager = "employeeCacheManager")
    public Employee getEmp(Integer id) {
        Employee employee = employeeMapper.getEmployeeById(id);
        System.out.println("查询 Employee: " + employee);
        return employee;
    }

    /**
     * 更新
     * @param employee
     * 1. 先调用方法, 再缓存
     * @return
     */
//    @CachePut(value = {"emp"}, key = "#root.method.name + '[' + #result.id + ']'")
    @CachePut(value = {"emg"}, key = "#employee.id")
    public Employee update(Employee employee) {
        employeeMapper.updateEmployee(employee);
        return employee;
    }

    @Cacheable
    public Employee getEmgByName(String name) {
        return  employeeMapper.getEmployeeByName(name);
    }


    // 直接编码使用缓存

    @Qualifier("employeeCacheManager")
    @Autowired
    RedisCacheManager employeeCacheManager;

    public Employee getEmployee(Integer id) {
        Employee employee = employeeMapper.getEmployeeById(id);
        System.out.println("查询 Employee: " + employee);
        Cache cache = employeeCacheManager.getCache("employee");
        cache.put("employee:" + id, employee);

        return employee;
    }
}
